package com.caisejingyu.whales.common.utils;

import android.app.Application;
import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.res.Configuration;
import android.support.annotation.NonNull;
import android.util.DisplayMetrics;

/**
 * 屏幕密度工具类，用于适配
 *
 * @author yuzhouxu
 * @date 2018/6/21
 */
@SuppressWarnings({"WeakerAccess", "unused"})
public final class WindowDensityUtil {

    private static float sDensity;
    private static float sScaledDensity;

    private static TargetDensityHolder sTargetDensityHolder = new TargetDensityHolder() {
        @Override
        public float getDensity(DisplayMetrics metrics) {
            return metrics.heightPixels / 720F;
//            return metrics.widthPixels / 960F;
        }
    };


    public static void setCustomDensity(@NonNull Context activity, @NonNull final Application application) {
        DisplayMetrics metrics = application.getResources().getDisplayMetrics();
        if (sDensity == 0) {
            sDensity = metrics.density;
            sScaledDensity = metrics.scaledDensity;
            application.registerComponentCallbacks(new ComponentCallbacks() {
                @Override
                public void onConfigurationChanged(Configuration newConfig) {
                    if (newConfig != null && newConfig.fontScale > 0) {
                        sScaledDensity = application.getResources().getDisplayMetrics().scaledDensity;
                    }
                }

                @Override
                public void onLowMemory() {}
            });
        }

        final float targetDensity = sTargetDensityHolder.getDensity(metrics);

        final float targetScaledDensity = targetDensity * (sScaledDensity / sDensity);
        final int targetDensityDpi = (int) (160 * targetDensity);
        metrics.density = targetDensity;
        metrics.scaledDensity = targetScaledDensity;
        metrics.densityDpi = targetDensityDpi;

        DisplayMetrics activityMetrics = activity.getResources().getDisplayMetrics();
        activityMetrics.density = targetDensity;
        activityMetrics.scaledDensity = targetScaledDensity;
        activityMetrics.densityDpi = targetDensityDpi;
    }

    public static void setTargetDensityHolder(@NonNull TargetDensityHolder targetDensityHolder) {
        sTargetDensityHolder = targetDensityHolder;
    }

    interface TargetDensityHolder {

        float getDensity(DisplayMetrics metrics);
    }
}

